package web.servlet.userlist.service;

import web.servlet.userlist.dao.UserDao;
import web.servlet.userlist.dao.UserDaoImpl;
import web.servlet.userlist.domin.PageBean;
import web.servlet.userlist.domin.User;

import java.util.List;

/**
 * @Author: 18148
 * @Date: 2020-06-21 15:58:17
 */
public class UserServiceImpl implements UserService {
    UserDao dao = new UserDaoImpl();

    @Override
    public List<User> findAll() {
        List<User> users = dao.selectAll();
        return users;
    }

    @Override
    public int add(User user) {
        User user1 = dao.selectByName(user.getName());
        if (user1 == null) {
            int i = dao.insert(user);
            return i;
        } else {
            return -1;
        }
    }

    @Override
    public int delete(int id) {
        int i = dao.delete(id);
        return i;
    }

    @Override
    public User selectById(int id) {
        User user = dao.selectById(id);
        return user;
    }

    @Override
    public int update(int id, User user) {
        int i = dao.update(id, user);
        return i;
    }

    @Override
    public User login(User user) {
        return dao.selectByNameAndPassword(user);

    }

    @Override
    public void delSelected(String[] uid) {
        if (uid != null && uid.length > 0) {
            for (String s :
                    uid) {
                int i = Integer.parseInt(s);
                dao.delete(i);
            }
        }
    }

    @Override
    public PageBean<User> findUserByPage(String cuttentPage, String rows) {
        PageBean<User> pb = new PageBean<User>();
        int c = Integer.parseInt(cuttentPage);
        if(c<=0){
            c=1;
        }
        int r = Integer.parseInt(rows);

        pb.setRows(r);
        int totalCount=dao.selectTotalCount();
        pb.setTotalCount(totalCount);
        int s=(c-1)*r;
        List<User> list=dao.selectByPage(s,r);
        pb.setList(list);
        int totalPage=(totalCount/r)==0?totalCount/r:totalCount/r+1;
        if(c>=totalPage){
            c=totalPage;
        }
        pb.setCuttentPage(c);
        pb.setTotalPage(totalPage);
        return pb;
    }
}
